package com.list;

/**
 * 循环链表:
 * head -> 1 -> 2 -> 3 -> 4 -> 1 -> ...
 * 这样,从 4向后指,就直接返回到了1,而 1.next又是 2 ,形成循环
 * 因此最后一个节点的 next = head.next 就好
 * 注意这样的链表中没有 prev (指向前一个元素)指针
 */
public class CircularList implements ILinkedList {

    LinkedNode head;
    int count;  //记录节点个数,因为此时寻找最后一个元素时不能通过 node.next == null 来判断

    @Override
    public void insert(int key) {
        LinkedNode node = new LinkedNode(key);
        if (!isEmpty()) {
            //将新节点添加入链表中
            node.next = head.next;
            head.next = node;
            //更新最后一个节点的 next
            LinkedNode temp = new LinkedNode(0);
            temp.next = head.next;
            for (int i = 0; i <= count; i++) {
                temp = temp.next;
            }
            temp.next = head.next;
        } else {
            head.next = node;
            node.next = head.next;
        }
        count++;
    }

    @Override
    public int delete() {
        assert !isEmpty();
        LinkedNode p = new LinkedNode(0);
        p.next = head.next;
        int key = 0;
        for (int i = 0; i < count - 1; i++) {
            //现在 p.next.next 为 null,即 p -> p.next -> null ,现在要删除 p.next , 同时满足循环链表的性质
            p = p.next;
        }
        key = p.next.key;
        count--;
        return key;
    }

    @Override
    public boolean isEmpty() {
        return head.next == null;
    }

    public CircularList() {
        count = 0;
        head = new LinkedNode(0);
    }
}
